package com.fanshuai2.niuke.search.dfs;

import java.util.ArrayList;
import java.util.List;

public class Permute {

    static boolean allVisited(boolean[] visited) {
        boolean all = true;
        for (int i = 0; i < visited.length; i++) {
            if (!visited[i]) {
                all = false;
            }
        }
        return all;
    }

    static List<String> permute(int n) {
        char[] arr = new char[n];
        for (int i = 0; i < n; i++) {
            arr[i] = (char) (i + 1 + '0');
        }

        boolean[] visited = new boolean[n];
        List<String> permutes = new ArrayList<>();
        StringBuilder b = new StringBuilder();
        dfs(arr, visited, b, permutes);
        System.out.println("b=" + b);
        return permutes;
    }

    static void dfs(char[] arr, boolean[] visited, StringBuilder path, List<String> permutes) {
        if (allVisited(visited)) {
            permutes.add(path.toString());
            return;
        }

        for (int i = 0; i < arr.length; i++) {
            if (!visited[i]) {
                visited[i] = true;
                path.append(arr[i]);

                dfs(arr, visited, path, permutes);

                path.deleteCharAt(path.length() - 1);
                visited[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(permute(4));
    }
}
